import { TextModel, SelectionModel } from "../models";

/**视图渲染 */
export class SourceView {
    private _textModel :TextModel;
    private _selectionModel :SelectionModel;
    private _viewContainer:HTMLElement;

    constructor (textModel: TextModel, selectionModel: SelectionModel, viewContainer: HTMLElement) {
        this._textModel = textModel
        this._selectionModel = selectionModel
        this._viewContainer = viewContainer
        const htmlEle = document.getElementById('myEditor') || document.body
        const childEle = document.getElementById('source-preview')
        if(childEle){
            htmlEle.removeChild(childEle)
        }
        this.addEventListener()
    }

    getViewContainer(){
        return this._viewContainer
    }

    getTextModel(){
        return this._textModel
    }

    addEventListener () {
        /**订阅text-change */
        this._textModel.on('text-change', this.render.bind(this))
    }
    updateDomSelection () {
        const domSelection = window.getSelection()
        if (domSelection) {
            const selectionFromModel = this._selectionModel.getSelection()
            const anchor = selectionFromModel.anchor
            const range = window.document.createRange()
            range.setStart(this._viewContainer.childNodes[0] || this._viewContainer, anchor)
            range.setEnd(this._viewContainer.childNodes[0] || this._viewContainer, anchor)
            domSelection.removeAllRanges()
            domSelection.addRange(range)  
        }
        
    }
    render () {
        /**渲染页面 */
        this._viewContainer.innerHTML = this._textModel.getSpacers() + '\n'
        /**出现首位置光标渲染问题 */
        Promise.resolve().then(() => {
            /**更新偏移量 */
            this.updateDomSelection()
        })
    }
}